<template>
  <div id="container">
    <div style="position: absolute; left: 0">
      <button @click="moveCamera">移动相机</button>
      <button @click="moveCube">移动物体</button>
    </div>
  </div>
</template>

<script setup>
import * as THREE from "three";
// import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { onMounted } from "vue";

// 创建场景
// 场景能够让你在什么地方、摆放什么东西来交给three.js来渲染，这是你放置物体、灯光和摄像机的地方。
const scene = new THREE.Scene();
// 添加背景颜色
scene.background = new THREE.Color(0x666666);

// 添加雾
// scene.fog = new THREE.Fog(0xcccccc, 10, 15)

// 创建立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
// 网格
const cube = new THREE.Mesh(geometry, material);
cube.position.set(3, 3, 0);
scene.add(cube);

// 添加网格地面
const gridHelper = new THREE.GridHelper(10, 10);
scene.add(gridHelper);

// 创建相机
const camera = new THREE.PerspectiveCamera();
camera.position.y = 5;
camera.position.z = 10;
console.log(cube, 'cube')
camera.lookAt(3,3,0)

const moveCamera = () => {
  camera.position.y = 15;
  // camera.position.z = 20;
  camera.lookAt(cube.position)
  
};

const moveCube = () => {
  cube.position.set(3, 5, 0);
  // 看向物体
  // console.log(controls)
  // controls.target = cube.position

  camera.lookAt(cube.position)
};

// 创建渲染器
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
// 添加轨道控制器
  // const controls = new OrbitControls(camera, renderer.domElement);
onMounted(() => {
  console.log(2222)
  
  // 将渲染器添加到页面
  document.getElementById("container").appendChild(renderer.domElement);

  

  // // 添加阻尼
  // controls.enableDamping = true;
  // controls.dampingFactor = 0.01;

  // controls.addEventListener('change', function() {
  //   console.log(camera.toJSON())
  // })
  // 自动旋转
  // controls.autoRotate = true;
  // controls.autoRotateSpeed = 0.5;

  // 进行渲染
  // renderer.render(scene, camera);

  // 让立方体动起来
  function animate() {
    // 告诉浏览器——你希望执行一个动画，并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数，该回调函数会在浏览器下一次重绘之前执行。
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    // 轨道控制器更新
    // controls.update();
    renderer.render(scene, camera);
  }
  animate();
});
</script>